package javase_class_250912;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * ClassName: StringAPIDemo
 * Package: javase_class_250912
 * Description:
 *
 * @Author harkjeans
 * @Create 2025/9/12 10:28
 * @Version 1.0
 */
public class StringAPIDemo {
    public static void main(String[] args) {
        // 构造方法
        String str = "  Hello World  ";
        System.out.println("strID = " + System.identityHashCode(str));//strID = 2003749087

        char[] chars = {'H', 'e', 'l', 'l', 'o'};
        String str1 = new String(chars);               // "Hello"
        String str2 = new String(chars, 0, 3);         // "Hel" (offset, count)
        String str3 = String.copyValueOf(chars);       // "Hello"
        String str4 = String.copyValueOf(chars, 0, 3); // "Hel"
        System.out.println("str1ID = " + System.identityHashCode(str1));//str1ID = 1480010240
        System.out.println("str2ID = " + System.identityHashCode(str2));//str2ID = 81628611
        System.out.println("str3ID = " + System.identityHashCode(str3));//str3ID = 1828972342
        System.out.println("str4ID = " + System.identityHashCode(str4));//str4ID = 1452126962

        byte[] bytes = {72, 101, 108, 108, 111}; // "Hello" 的ASCII码
        //String str5 = new String(bytes, "GBK");不推荐
        String str5 = new String(bytes, StandardCharsets.UTF_8); // 推荐方式
        System.out.println(str5);//Hello
        System.out.println("str5ID = " + System.identityHashCode(str5));//str5ID = 931919113

        // 基本信息
        System.out.println("长度: " + str.length()); // 13
        System.out.println("去空白: '" + str.trim() + "'"); // 'Hello World'
        System.out.println(str.toUpperCase());     // "HELLO WORLD"
        System.out.println(str.toLowerCase());     // "hello world"
        System.out.println(str.concat("hark"));

        // 查找和判断
        System.out.println("包含World: " + str.contains("World")); // true
        System.out.println("第一个o的位置: " + str.indexOf('o')); // 5

        // 截取和分割
        System.out.println("子串: " + str.substring(2, 7)); // "Hello"
        String[] parts = "a,b,c".split(",");
        System.out.println("分割: " + Arrays.toString(parts)); // [a, b, c]

        // 转换
        System.out.println("大写: " + str.toUpperCase()); // "  HELLO WORLD  "
        System.out.println("替换: " + str.replace("World", "Java")); // "  Hello Java  "

        // 格式化
        String info = String.format("姓名: %s, 年龄: %d", "张三", 20);
        System.out.println(info); // "姓名: 张三, 年龄: 20"
    }
}
